package com.wee.aircoach_user;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.android.volley.toolbox.ImageLoader;
import com.bigtotoro.util.DeviceUtil;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.widgets.AppProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.wee.entity.MD5Util;
import com.wee.entity.Tools;
import com.wee.entity.User_detail;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import de.hdodenhof.circleimageview.CircleImageView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class ProfileInfoActivity extends Activity implements View.OnClickListener {
    private User_detail data1;
    private CircleImageView imagePhoto;
    private TextView gender,birthday,height,weight,name,submit;
    private OSS oss;
    String  file_name="";
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private static final int PHOTO_CLIP = 3;
    private String imgPahth="";
    private String imgURL="http://image-test.aircoach.cn/image/";
    //birthday
    private DatePickerDialog datePickerDialog;
    private String dateStr = "1987-01-01";
    int  it;
    private int random,exact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info);
        random=new Random().nextInt(9999);
        exact=  SharedPreferencesUtil.getInt(this, Constant.USERTIME);
        initView();
        gethttp();
    }


    /** 解析字段 */
    public void gethttp() {
        it=  SharedPreferencesUtil.getInt(ProfileInfoActivity.this,Constant.USERID);
        String  user_main=Constant.USER_DETAIL+ MD5Util.md5(exact)+"&id="+it+"&ver" + random;
        HttpUtils httpUtils = new HttpUtils();
  //      AppProgressBar.checkAndCreateProgressBar(this);
        httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(com.lidroid.xutils.http.ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            try {
                                data1 = gs.fromJson(object, User_detail.class);
                                name.setText("" + data1.getName());
                                height.setText("" + data1.getHeight());
                                weight.setText("" + data1.getWeight());
                                birthday.setText("" + data1.getBirthday());
                                dateStr = data1.getBirthday();
                                if (data1.getFigure() != null && data1.getFigure().length() != 0) {
                                    MyApplication.getInstance().getImageLoader().get(data1.getFigure(), ImageLoader.getImageListener(imagePhoto, R.drawable.coach_no, R.drawable.coach_no), 300, 300);
                                }
                                if (data1.getGender().equals("male")) {
                                    gender.setText("男");
                                } else {
                                    gender.setText("女");
                                }
                            } catch (Exception r) {

                            }
                            //                     AppProgressBar.closeProgressBar();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                        //               AppProgressBar.closeProgressBar();
                    }
                });

    }
    private void initView() {
        oss = new OSSClient(ProfileInfoActivity.this, Tools.ENDPOINT,Tools.credetialProvider);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次


        findViewById(R.id.back).setOnClickListener(this);
        submit= (TextView)findViewById(R.id.submit);
        submit.setOnClickListener(this);
        name = (TextView)findViewById(R.id.name);

        findViewById(R.id.layout_height).setOnClickListener(this);
        findViewById(R.id.layout_weight).setOnClickListener(this);
        findViewById(R.id.layout_birth).setOnClickListener(this);

        height = (TextView)findViewById(R.id.height);
        weight = (TextView)findViewById(R.id.weight);
        birthday= (TextView)findViewById(R.id.birthday);
        gender= (TextView)findViewById(R.id.gender);

        imagePhoto = (CircleImageView)findViewById(R.id.avatar);
        imagePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSystemPickerDialog();
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
             /*   Intent it = new Intent(this, SettingActivity.class);
                it.putExtra("path", data1.getFigure());
                startActivity(it);*/
                finish();
                break;
            case R.id.layout_height:
                NumberPicker mPicker = new NumberPicker(this);
                mPicker.setMinValue(145);
                mPicker.setMaxValue(190);
                mPicker.setValue(165);
                mPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        // TODO Auto-generated method stub
                        height.setText(String.valueOf(newVal));
                        int number = Integer.parseInt(String.valueOf(newVal));

                    }
                });

                AlertDialog mAlertDialog = new AlertDialog.Builder(this)
                        .setTitle("身高(Cm)").setView(mPicker).setPositiveButton("ok",null).create();
                mAlertDialog.show();
                break;
            case R.id.layout_weight:
                NumberPicker mPicker1 = new NumberPicker(this);
                mPicker1.setMinValue(45);
                mPicker1.setMaxValue(110);
                mPicker1.setValue(50);
                mPicker1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        // TODO Auto-generated method stub
                        weight.setText(String.valueOf(newVal));
                        //     Weight(String.valueOf(newVal));
                        int number1 = Integer.parseInt(String.valueOf(newVal));
                    }
                });
                AlertDialog mAlertDialog1 = new AlertDialog.Builder(this)
                        .setTitle("体重(Kg)").setView(mPicker1).setPositiveButton("ok",null).create();
                mAlertDialog1.show();
                break;
            case R.id.layout_birth:
                if(datePickerDialog==null){
                    datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            dateStr = formatDate(year, monthOfYear, dayOfMonth);
                            birthday.setText(dateStr);
                        }
                    }, 1987,0,1);
                    dateStr = "1987-01-01";
                }
                datePickerDialog.show();
                break;
            //提交
            case R.id.submit:
                AppProgressBar.checkAndCreateProgressBar(ProfileInfoActivity.this);
                if(file_name.length()!=0){
                    Toast.makeText(this, "头像上传中",Toast.LENGTH_SHORT).show();
                 /*   AppProgressBar.checkAndCreateProgressBar(ProfileInfoActivity.this);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            asyncPutObjectFromLocalFile();

                        }
                    }, 1000);
                    AppProgressBar.closeProgressBar();*/
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            asyncPutObjectFromLocalFile();
                        }
                    }).start();

                }
                AppProgressBar.closeProgressBar();
                    register();

                //post

                break;
        }
    }
    private void register(){
        String hei=height.getText().toString().trim();
        String wei=weight.getText().toString().trim();
        if(hei.length()==0 ){
            Toast.makeText(this, "身高不能为空且为数字",Toast.LENGTH_SHORT).show();
            return;
        }
        if(wei.length()==0){
            Toast.makeText(this, "体重不能为空且为数字",Toast.LENGTH_SHORT).show();
            return;
        }
        if(dateStr.length()==0){
            Toast.makeText(this, "请选择生日",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
     //   AppProgressBar.checkAndCreateProgressBar(this);
        params.addBodyParameter("id",it+"");
        if(file_name.length()!=0){
            params.addBodyParameter("figure",imgURL+file_name);
        }
        params.addBodyParameter("token", ""+ MD5Util.md5(exact));
        // params.addBodyParameter("name", nam);
        //params.addBodyParameter("gender", gender);
        params.addBodyParameter("birthday", dateStr);
        params.addBodyParameter("weight", wei);
        params.addBodyParameter("height", hei);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Constant.UPDATE_USER_INFOR,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        JSONObject json;
                        try {
                            json = new JSONObject(str);
                            if(json.getString("status").equals("ok")){
                                gethttp();
                                Toast.makeText(ProfileInfoActivity.this,"正在修改",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(ProfileInfoActivity.this,"修改失败",Toast.LENGTH_SHORT).show();
                            }
                            file_name="";
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
               //         AppProgressBar.closeProgressBar();
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                //        AppProgressBar.closeProgressBar();
                    }
                });
    }
    private static String formatDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(0);
        cal.set(year, month, day);
        Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public void asyncPutObjectFromLocalFile() {
        // TODO Auto-generated method stub
        // 构造上传请求
    //    AppProgressBar.checkAndCreateProgressBar(this);
        PutObjectRequest put = new PutObjectRequest(Tools.testBucket, "image/"+file_name, imgPahth);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
      //          AppProgressBar.closeProgressBar();
                Toast.makeText(ProfileInfoActivity.this, "图片上传成功",Toast.LENGTH_SHORT).show();
             //   register();
                /**如果成功上传服务器 那就能提交表单**/
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
         //       AppProgressBar.closeProgressBar();
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

        // task.cancel(); // 可以取消任务

        // task.waitUntilFinished(); // 可以等待直到任务完成

    }
    //拾取照片
    private void showSystemPickerDialog(){

        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
// 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
// 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,1);
// 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/M ultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
// 默认选择图片,回填选项(支持String ArrayList)
        //intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, 1);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if(path != null && path.size()>0){
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showStubImage(R.drawable.coach_no)
                        .showImageForEmptyUri(R.drawable.coach_no)
                        .cacheInMemory()
                        .cacheOnDisc()
                        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                        .build();
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file://" + path.get(0), imagePhoto, options);
                try{
                String about_path= path.get(0);
                Bitmap bitmap=revitionImageSize(about_path);
                String url= Environment
                        .getExternalStorageDirectory().getAbsolutePath()
                        + "/ImgAirCoach";
                String url1= url+"/uu_user_img_"+(DeviceUtil.getUUID(this)+5)+random+".jpg";
                File f=new File(url);
               if(!f.exists()){
                   try {
                       //按照指定的路径创建文件夹
                       f.mkdirs();
                   } catch (Exception e) {
                       // TODO: handle exception
                   }

               }
                saveBitmap(ProfileInfoActivity.this, bitmap, url1);
                }catch (Exception r){
                    Toast.makeText(this,"系统相机异常",Toast.LENGTH_SHORT).show();
                }
            }

        }

    }
  /*  private static Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 200f;//这里设置高度为800f
        float ww = 200f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;//压缩好比例大小后再进行质量压缩
    }*/
    public static Bitmap revitionImageSize(String path){
        try{
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            in.close();
            int i = 0;
            Bitmap bitmap = null;
            while (true) {
                if ((options.outWidth >> i <= 1000)
                        && (options.outHeight >> i <= 1000)) {
                    in = new BufferedInputStream(
                            new FileInputStream(new File(path)));
                    options.inSampleSize = (int) Math.pow(2.0D, i);
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    break;
                }
                i += 1;
            }
            return bitmap;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;

    }
    public  void saveBitmap(Context context, Bitmap bm, String path) {
        Log.e("", "保存图片");
        try {
            File f = new File(path);
            file_name=f.getName();
            imgPahth=f.getPath();
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            if (bm != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }
            out.flush();
            out.close();
            Log.e("", "已经保存");
			/*
			 * if(bm != null){ if(!bm.isRecycled()){//回收图片所站的内存 bm.recycle();
			 * System.gc();//提醒系统及时回收 } }
			 */

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




}
